import { ObjectDirective } from "vue";

const longPress: ObjectDirective = {
  mounted(el: any, binding: any, vNode: any) {
    const { handler: handleFun, params } = binding.value;
    let action = "";
    if (typeof handleFun !== "function") {
      const compName = vNode.context?.name;
      let warn = `[longpress:] provided expression '${binding.expression}' is not a function, but has to be`;
      if (compName) {
        warn += ` Found in component '${compName}'`;
      }
      console.warn(warn);
    }

    let pressTimer: any = null;
    let startTime: number;
    let endTime: number;
    let moved = false; // 🚀 记录是否滑动
    let startX = 0;
    let startY = 0;

    // 触摸开始
    const start = (e: TouchEvent | MouseEvent) => {
      if (e.type === "click" && "button" in e && e.button !== 0) {
        return;
      }

      moved = false; // 🔥 重置滑动标记
      startTime = new Date().getTime();

      if ("touches" in e) {
        startX = e.touches[0].clientX;
        startY = e.touches[0].clientY;
      }

      // 🚀 500ms 后执行长按逻辑
      pressTimer = setTimeout(() => {
        if (!moved) {
          action = "longPress";
          handler(e);
        }
      }, 500);
    };

    // 触摸移动
    const move = (e: TouchEvent) => {
      if (!pressTimer) return;

      const diffX = Math.abs(e.touches[0].clientX - startX);
      const diffY = Math.abs(e.touches[0].clientY - startY);

      // 🔥 如果滑动超过 10px，判定为滑动，取消长按逻辑
      if (diffX > 10 || diffY > 10) {
        moved = true;
        clearTimeout(pressTimer);
        pressTimer = null;
      }
    };

    // 触摸结束
    const end = (e: TouchEvent | MouseEvent) => {
      endTime = new Date().getTime();
      action = endTime - startTime > 500 ? "longPress" : "click";

      if (pressTimer !== null) {
        clearTimeout(pressTimer);
        pressTimer = null;
      }

      if (action === "click" && !moved) {
        handler(e);
      }
    };

    // 事件处理函数
    const handler = (e: TouchEvent | MouseEvent) => {
      let location;
      if ("touches" in e) {
        location = {
          clientX: e.changedTouches[0].clientX,
          clientY: e.changedTouches[0].clientY,
        };
      } else {
        location = { clientX: (e as MouseEvent).clientX, clientY: (e as MouseEvent).clientY };
      }
      binding.value.handler(location, action, params);
    };

    // 添加事件监听器
    el.addEventListener("mousedown", start);
    el.addEventListener("touchstart", start, { passive: false });
    el.addEventListener("touchmove", move, { passive: false }); // 监听滑动
    el.addEventListener("touchend", end);
    el.addEventListener("touchcancel", end);
    el.addEventListener("mouseup", end);
    el.addEventListener("mouseout", end);
    el.addEventListener("click", end);
  },
};

export default longPress;
